import { BizKfExtraProColumnType } from '@/components';
import * as API from '@/services';
import { Divider, message, Space, Typography } from 'antd';
import {getBooleanToProTableValueEnum, KfModal, KfPagingTablePage, KfPagingTablePagePropsAction, useBackendEnum} from 'kf-web-library';
import React, { useRef } from 'react';
import { useLocation, useAccess } from 'umi';
import QuickForm from './components/QuickForm';
import './index.less';
import defaultPlaceHolderImg from '@/assets/default_placeholder.png';
import { CheckCircleOutlined, EditOutlined, RocketOutlined } from '@ant-design/icons';

type Entity = API.News;
type EntityPageQueryParams = API.NewsPageQueryParams;
const entityTypeName = '新闻';
const EntityQuickForm = QuickForm;

interface EntityTableListProps {}

/**
 * 新闻 列表页面
 */
const EntityTableList: React.FC<EntityTableListProps> = (props) => {
  const location = useLocation();
  const access = useAccess();
  const { enumDict, enumTypeDict, getBackendEnum } = useBackendEnum();
  const actionRef = useRef<KfPagingTablePagePropsAction<Entity, EntityPageQueryParams>>();

  return (
    <KfPagingTablePage<Entity, EntityPageQueryParams, BizKfExtraProColumnType>
      actionRef={actionRef}
      entityTypeName={entityTypeName}
      pagingQuery={(p) => {
        return API.queryNewss({ ...p, type: ['COMPETITION', 'JOBS', 'P_FRAUD', 'OTHER'] });
      }}
      opActionsDef={{
        single: {
          deleteOne: (record) => {
            KfModal.deleteConfirm(record.id, () => {
              API.deleteNews(record.id!).then((res) => {
                if (res.flag) {
                  message.info('删除成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
          upOne: (record) => {
            KfModal.confirm("上架", record.title as string, () => {
              API.upNews(record.id!).then((res) => {
                if (res.flag) {
                  message.info('上架成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
          downOne: (record) => {
            KfModal.confirm("下架", record.title as string, () => {
              API.downNews(record.id!).then((res) => {
                if (res.flag) {
                  message.info('下架成功');
                  actionRef.current?.reload();
                }
              });
            });
          }
        },
        multi: {
          deleteMultiple: (records) => {
            KfModal.batchActionConfirm('删除', records.length, () => {
              API.deleteNewss(records.map((r) => r.id!)).then((res) => {
                if (res.flag) {
                  message.info('批量删除成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
        },
      }}
      opFloatingsDef={{
        noargs: {
          createModal: {
            show: true,
            buttonText: '新增',
            fltRender: () => ({
              title: `新建`,
              content: <EntityQuickForm formType={'create'} />,
            }),
          },
        },
        single: {
          modifyModal: (record) => ({
            title: `编辑`,
            width: 800,
            content: <EntityQuickForm formType={'modify'} bizId={record.id} />,
          }),
          viewModal: (record) => ({
            fltType: 'modal',
            width: 800,
            title: `查看`,
            content: <EntityQuickForm formType={'view'} bizId={record.id} />,
          }),
        },
      }}
      proTable={{
        tableBarActions: (action, rows) => {
          return [];
        },
        search: {
          optionRender: (searchConfig, formProps, dom) => [...dom],
        },
      }}
      columns={[
        {
          title: '关键字',
          dataIndex: 'searchText',
          sorter: false,
          hideInTable: true,
          hideInForm: true,
          fieldProps: {
            placeholder: '标题',
          },
        },
        {
          title: '序号',
          width: 50,
          key: '_seq_index_',
          align: 'center',
          hideInSearch: true,
          valueType: 'index',
          render: (dom, record, index) => {
            const pageInfo = actionRef.current?.queryParams();
            return ((pageInfo?.current || 1) - 1) * (pageInfo?.pageSize || 0) + (index + 1);
          },
        },
        {
          title: '封面',
          dataIndex: nameof<Entity>((x) => x.img),
          sorter: false,
          hideInSearch: true,
          width: 120,
          align: 'center',
          valueType: 'image',
          fieldProps: {
            width: 88,
            height: 50,
            fallback: defaultPlaceHolderImg,
          },
        },
        {
          title: '标题',
          dataIndex: nameof<Entity>((x) => x.title),
          sorter: false,
          hideInSearch: true,
        },
        {
          title: '类型',
          width: 100,
          ellipsis: true,
          dataIndex: nameof<Entity>((x) => x.type),
          hideInSearch: false,
          kfValueEnum: 'NewsType',
          fieldProps: {
            exclude: ['HOME_CAROUSEL','AD_CAROUSEL'],
          },
        },
        {
          title: '来源',
          width: 100,
          ellipsis: true,
          dataIndex: nameof<Entity>((x) => x.source),
          hideInSearch: true,
        },
        {
          title: '状态',
          dataIndex: 'opened',
          sorter: false,
          hideInSearch: false,
          hideInTable: true,
          valueEnum: getBooleanToProTableValueEnum('已上架', '未上架'),
        },
        {
          title: '模式',
          dataIndex: 'mode',
          sorter: false,
          hideInSearch: false,
          hideInTable: true,
          kfValueEnum: "NewsMode"
        },
        {
          title: '上架时间',
          dataIndex: 'openedTime',
          sorter: false,
          hideInSearch: false,
          hideInTable: true,
          valueType: "dateRange"
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          sorter: false,
          hideInSearch: false,
          hideInTable: true,
          valueType: "dateRange"
        },
        {
          title: '更新/上架',
          dataIndex: nameof<Entity>((x) => x.createTime),
          width: 200,
          align: 'center',
          sorter: false,
          hideInSearch: true,
          ellipsis: true,
          render: (_, record) => {
            return (
              <Space direction={'vertical'}>
                <div>
                  <EditOutlined /> {record.modifyTime}
                </div>
                {record.openedTime && (
                  <div>
                    <CheckCircleOutlined /> {record.openedTime}
                  </div>
                )}

              </Space>
            );
          },
        },
        {
          title: '操作',
          fixed: 'right',
          width: 130,
          dataIndex: 'option',
          valueType: 'option',
          render: (_, record) => (
            <Space size={0} split={<Divider type="vertical" />}>
              {
                record.opened ? (
                  <a onClick={() => actionRef.current?.executeAction.single?.downOne(record)}>
                    <Typography.Text type="danger">下架</Typography.Text>
                  </a>
                ) : (
                  <a onClick={() => actionRef.current?.executeAction.single?.upOne(record)}>
                    <Typography.Text type="success">上架</Typography.Text>
                  </a>
                )
              }
              <a
                onClick={() => {
                  actionRef.current?.openFloating.single?.modifyModal(record, 'modal')
                }}
              >
                编辑
              </a>
              <a onClick={() => actionRef.current?.executeAction.single?.deleteOne(record)}>
                <Typography.Text type="danger">删除</Typography.Text>
              </a>
            </Space>
          ),
        },
      ]}
    />
  );
};

export default EntityTableList;
